package com.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author wangfengchen
 */
@Slf4j
@Component
public class LocalCacheUtil {


  @Autowired
  private CacheManager cacheManager;


  /**
   * 添加缓存
   *
   * @param cacheName 缓存名称
   * @param key       缓存key
   * @param value     缓存值
   */
  public void put(String cacheName, Object key, Object value) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache != null) {
      cache.put(key, value);
    }
  }

  /**
   * 获取缓存
   *
   * @param cacheName 缓存名称
   * @param key       缓存key
   * @return
   */
  public Optional<Object> get(String cacheName, Object key) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache == null) {
      return Optional.empty();
    }
    Cache.ValueWrapper valueWrapper = cache.get(key);
    if (null == valueWrapper) {
      return Optional.empty();
    }
    return Optional.ofNullable(valueWrapper.get());
  }

  /**
   * 失效缓存
   *
   * @param cacheName 缓存名称
   * @param key       缓存key
   */
  public void delete(String cacheName, Object key) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache != null) {
      cache.evict(key);
    }
  }

  /**
   * 清除所有缓存
   *
   * @param cacheName
   */
  public void clear(String cacheName) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache != null) {
      cache.clear();
    }
  }


}
